<!--#layout name=mail-->
<div id="app">
  <div class="page-header">
    <h1 class="title">Compose</h1>
  </div>
  <kb-form
    :model="model"
    :rules="rules"
    ref="form"
    v-if="contentLoaded"
    simple
    class="form-horizontal"
  >
    <kb-form-item prop="address" class="form-group">
      <template v-slot="data">
        <label class="control-label col-md-1">MAIL_FROM</label>
        <div
          class="col-md-11"
          v-kb-tooltip:left.manual.error="data.error"
          :class="{'has-error':data.error}"
        >
          <select class="form-control" v-model="model.address">
            <option
              v-for="(item,index) in addresses"
              :key="index"
              :value="item.id"
              >{{item.address}}</option
            >
          </select>
        </div>
      </template>
    </kb-form-item>
    <kb-form-item prop="receiverAddresses" class="form-group">
      <template v-slot="data">
        <label class="control-label col-md-1">MAIL_TO</label>
        <div
          class="col-md-11"
          id="receiver_addresses"
          v-kb-tooltip:left.manual.error="data.error"
          :class="{'has-error':data.error}"
          data-container="#receiver_addresses"
        >
          <select
            style="width: 100%"
            multiple
            class="form-control"
            v-kb-select2="receiverAddresses"
          >
          </select>
          <span class="block-helper">
            <a
              href="javascript:;"
              @click="showCC=true"
              v-if="!showCC"
              tabindex="-1"
              class="margin-right-10"
              >Add CC</a
            >
            <a
              href="javascript:;"
              @click="showBCC=true"
              v-if="!showBCC"
              tabindex="-1"
              >Add Bcc</a
            >
          </span>
        </div>
      </template>
    </kb-form-item>
    <kb-form-item v-show="showCC" prop="ccAddresses" class="form-group">
      <template v-slot="data">
        <label class="control-label col-md-1">Cc</label>
        <div
          class="col-md-11"
          id="cc_addresses"
          v-kb-tooltip:left.manual.error="data.error"
          :class="{'has-error':data.error}"
          data-container="#cc_addresses"
        >
          <select
            style="width: 100%"
            multiple
            class="form-control"
            v-kb-select2="ccAddresses"
          >
          </select>
          <span class="block-helper">
            <a href="javascript:;" @click="showCC=false">Remove</a>
          </span>
        </div>
      </template>
    </kb-form-item>
    <kb-form-item v-show="showBCC" prop="bccAddresses" class="form-group">
      <template v-slot="data">
        <label class="control-label col-md-1">Bcc</label>
        <div
          class="col-md-11"
          id="bcc_addresses"
          :class="{'has-error':data.error}"
          v-kb-tooltip:left.manual.error="data.error"
          data-container="#bcc_addresses"
        >
          <select
            style="width: 100%"
            multiple
            v-kb-select2="bccAddresses"
            class="form-control"
          >
          </select>
          <span class="block-helper">
            <a href="javascript:;" @click="showBCC=false">Remove</a>
          </span>
        </div>
      </template>
    </kb-form-item>
    <kb-form-item prop="subject" class="form-group">
      <template v-slot="data">
        <label class="control-label col-md-1">Subject</label>
        <div
          class="col-md-11"
          id="subject"
          v-kb-tooltip:left.manual.error="data.error"
          :class="{'has-error':data.error}"
          data-container="#subject"
        >
          <input type="text" class="form-control" v-model="model.subject" />
        </div>
      </template>
    </kb-form-item>
    <kb-form-item class="form-group">
      <label class="control-label col-md-1">Attachment</label>
      <div class="col-md-11">
        <div class="file-list">
          <div class="btn-group pull-left margin-right-10">
            <a class="btn blue btn-file"
              >Select<input type="file" id="attachments"
            /></a>
          </div>
          <ul v-if="model.attachments.length" style="margin-bottom: 0;">
            <li v-for="($data,index) in model.attachments">
              <span>{{$data.fileName}}</span>
              <a href="javascript:;" @click="removeAttachment($data)"
                ><span class="fa fa-remove"></span
              ></a>
            </li>
          </ul>
        </div>
      </div>
    </kb-form-item>
    <kb-form-item class="form-group">
      <label class="control-label col-md-1">Content</label>
      <div class="col-md-11">
        <div v-kb-richeditor="richEditor" style="opacity: 0"></div>
      </div>
    </kb-form-item>
    <kb-form-item class="form-group">
      <div class="col-md-11 col-md-offset-1">
        <button @click="send" class="btn green margin-right-5">Send</button>
        <button @click="saveDraft" class="btn green margin-right-5"
          >Save draft</button
        >
        <button @click="cancel" class="btn gray">Cancel</button>
      </div>
    </kb-form-item>
  </kb-form>
</div>

<style>
  #receiver_addresses .tooltip {
    margin-top: -10px;
  }
</style>

<script>
  (function() {
    Kooboo.loadJS([
      "/_Admin/Scripts/components/kbForm.js",
      "/_Admin/Scripts/kooboo-web-editor/richEditor.min.js",
      "/_Admin/Scripts/components/tinymceMonaco/plugin.min.js",
      "/_Admin/Scripts/lib/select2.min.js"
    ]);
    Kooboo.loadCSS(["/_Admin/Styles/select2/select2.css"]);
  })();

  var mailRegex = /(((("[^"]*")|([^";<>\s]*))\s*<\s*[a-zA-Z0-9!#$%&'*+\-/=?^_`{|}~]+(\.[a-zA-Z0-9!#$%&'*+\-/=?^_`{|}~]+)*@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})\s*>)|([a-zA-Z0-9!#$%&'*+\-/=?^_`{|}~]+(\.[a-zA-Z0-9!#$%&'*+\-/=?^_`{|}~]+)*@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})))(\s*;\s*(((("[^"]*")|([^";<>\s]*))\s*<\s*[a-zA-Z0-9!#$%&'*+\-/=?^_`{|}~]+(\.[a-zA-Z0-9!#$%&'*+\-/=?^_`{|}~]+)*@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})\s*>)|([a-zA-Z0-9!#$%&'*+\-/=?^_`{|}~]+(\.[a-zA-Z0-9!#$%&'*+\-/=?^_`{|}~]+)*@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})))?)*/;

  var self = new Vue({
    el: "#app",
    data: function() {
      var self = this;
      return {
        receiverAddresses: {
          options: [],
          selected: [],
          noItemTip: Kooboo.text.mail.noAddressFound
        },
        ccAddresses: {
          options: [],
          selected: [],
          noItemTip: Kooboo.text.mail.noAddressFound
        },
        bccAddresses: {
          options: [],
          selected: [],
          noItemTip: Kooboo.text.mail.noAddressFound
        },
        addresses: [],
        showCC: false,
        showBCC: false,
        contentLoaded: false,
        model: {
          address: "",
          subject: "",
          attachments: [],
          receiverAddresses: [],
          ccAddresses: [],
          bccAddresses: []
        },
        backUp: null,
        richEditor: {
          value: "",
          editorConfig: {
            min_height: 300,
            max_height: 600
          },
          mailConfig: true
        },
        saveInDraft: false
      };
    },
    computed: {
      rules: function() {
        var self = this;
        return {
          address: [{ required: Kooboo.text.validation.required }],
          subject: self.saveInDraft
            ? []
            : [{ required: Kooboo.text.validation.required }],
          receiverAddresses: [
            {
              validate: function(value) {
                if (!value.length && !self.saveInDraft) return false;
                for (let i = 0; i < value.length; i++) {
                  const f = value[i];
                  if (!f.text || !mailRegex.test(f.text)) return false;
                }
                return true;
              },
              message: Kooboo.text.validation.containInvalidEmail
            }
          ],
          ccAddresses: [
            {
              validate: function(value) {
                if (!self.showCC) return true;
                for (let i = 0; i < value.length; i++) {
                  const f = value[i];
                  if (!f.text || !mailRegex.test(f.text)) return false;
                }
                return true;
              },
              message: Kooboo.text.validation.containInvalidEmail
            }
          ],
          bccAddresses: [
            {
              validate: function(value) {
                if (!self.showBCC) return true;
                for (let i = 0; i < value.length; i++) {
                  const f = value[i];
                  if (!f.text || !mailRegex.test(f.text)) return false;
                }
                return true;
              },
              message: Kooboo.text.validation.containInvalidEmail
            }
          ]
        };
      }
    },
    mounted: function() {
      var self = this;
      $.when(
        Kooboo.EmailAddress.getList(),
        Kooboo.EmailDraft.targetAddresses()
      ).then(function(lres, tres) {
        var res1 = lres[0],
          res2 = tres[0];

        if (res1.success) {
          self.addresses = res1.model;
          if (res1.model.length) {
            var _address = Kooboo.getQueryString("address");
            var _a = _.find(self.addresses, function(addr) {
              return addr.address == _address;
            });
            self.model.address = _a ? _a.id : res1.model[0].id;
          } else {
            window.info.fail(Kooboo.text.mail.noAddressYet);
          }
        }

        if (res2.success) {
          res2.model.forEach(function(user) {
            self.receiverAddresses.options.push(user.address);
            self.ccAddresses.options.push(user.address);
            self.bccAddresses.options.push(user.address);
          });
        }

        var messageId = Kooboo.getQueryString("messageId"),
          sourceId = Kooboo.getQueryString("sourceId"),
          editId = Kooboo.getQueryString("id"),
          type = Kooboo.getQueryString("type");

        if (type) {
          switch (type) {
            case "Drafts":
              Kooboo.EmailDraft.Compose({
                messageId: messageId
              }).then(function(res) {
                if (res.success) {
                  self.setData(res.model);
                }
              });

              break;
            case "Reply":
              Kooboo.EmailMessage.getReplyContent({
                sourceId: sourceId
              }).then(function(res) {
                if (res.success) {
                  self.setData(res.model);
                }
              });
              break;
            case "Forward":
              Kooboo.EmailMessage.getForwardContent({
                sourceId: sourceId
              }).then(function(res) {
                if (res.success) {
                  self.setData(res.model);
                }
              });
              break;
          }
        } else {
          Kooboo.EmailDraft.Compose().then(function(res) {
            if (res.success) {
              self.contentLoaded = true;
            }
          });
        }
      });
    },
    methods: {
      setData: function(data) {
        self.model.address = data.from;
        self.model.subject = data.subject;
        self.model.attachments = data.attachments;
        self.receiverAddresses.selected = data.to;

        data.to.forEach(function(f) {
          if (self.receiverAddresses.options.indexOf(f) == -1) {
            self.receiverAddresses.options.push(f);
          }
        });

        self.ccAddresses.selected = data.cc;
        self.showCC = !!data.cc.length;
        data.cc.forEach(function(f) {
          if (self.ccAddresses.options.indexOf(f) == -1) {
            self.ccAddresses.options.push(f);
          }
        });

        self.bccAddresses.selected = data.bcc;
        self.showBCC = !!data.bcc.length;
        data.bcc.forEach(function(f) {
          if (self.bccAddresses.options.indexOf(f) == -1) {
            self.bccAddresses.options.push(f);
          }
        });

        self.richEditor.value = data.html;
        self.backUp = JSON.parse(JSON.stringify(self.$data));
        self.contentLoaded = true;
      },
      isContentChanged: function() {
        if (!self.backUp) return false;
        function select2Value(data) {
          return data.selected
            .map(function(f) {
              if (typeof f == "string") return f;
              return f.text;
            })
            .join(",");
        }

        function attachmentValue(data) {
          return data
            .map(function(f) {
              return f.fileName;
            })
            .join(",");
        }

        if (
          select2Value(self.backUp.receiverAddresses) !=
          select2Value(self.receiverAddresses)
        ) {
          return true;
        }

        if (
          select2Value(self.backUp.ccAddresses) !=
          select2Value(self.ccAddresses)
        ) {
          return true;
        }

        if (
          select2Value(self.backUp.bccAddresses) !=
          select2Value(self.bccAddresses)
        ) {
          return true;
        }

        if (self.showCC != self.backUp.showCC) return true;
        if (self.showBCC != self.backUp.showBCC) return true;

        if (self.model.address != self.backUp.model.address) return true;

        if (self.model.subject != self.backUp.model.subject) return true;

        if (self.richEditor.value != self.backUp.richEditor.value) return true;

        if (
          attachmentValue(self.model.attachments) !=
          attachmentValue(self.backUp.model.attachments)
        )
          return true;
      },
      cancel: function() {
        if (self.isContentChanged()) {
          if (confirm(Kooboo.text.confirm.beforeReturn)) {
            self.goBack();
          }
        } else {
          self.goBack();
        }
      },
      goBack: function() {
        var folder = Kooboo.getQueryString("folder");
        location.href = Kooboo.Route.Get(
          folder
            ? Kooboo.Route.Email[folder + "Page"]
            : Kooboo.Route.Email.InboxPage
        );
      },
      getMailData: function() {
        var _data = {
          from: self.model.address,
          to: self.receiverAddresses.selected.map(function(f) {
            return f.text;
          }),
          cc: self.showCC
            ? self.ccAddresses.selected.map(function(f) {
                return f.text;
              })
            : [],
          bcc: self.showBCC
            ? self.bccAddresses.selected.map(function(f) {
                return f.text;
              })
            : [],
          subject: self.model.subject,
          html: self.richEditor.value,
          attachments: self.model.attachments
        };

        Kooboo.getQueryString("messageId") &&
          (_data["messageId"] = Kooboo.getQueryString("messageId"));

        return _data;
      },
      saveDraft: function() {
        self.saveInDraft = true;
        self.$nextTick(function() {
          if (self.$refs.form.validate()) {
            Kooboo.EmailDraft.Save(JSON.stringify(self.getMailData())).then(
              function(res) {
                if (res.success) {
                  if (!Kooboo.getQueryString("messageId")) {
                    location.href = Kooboo.Route.Get(
                      Kooboo.Route.Email.Compose,
                      {
                        messageId: res.model,
                        type: "Drafts",
                        folder: "Draft"
                      }
                    );
                  } else {
                    window.info.show(Kooboo.text.info.save.success, true);
                    self.backUp = JSON.parse(JSON.stringify(self.$data));
                  }
                } else {
                  window.info.show(Kooboo.text.info.save.fail, false);
                }
              }
            );
          }
        });
      },
      send: function() {
        self.saveInDraft = false;
        self.$nextTick(function() {
          if (self.$refs.form.validate()) {
            Kooboo.EmailMessage.Send(JSON.stringify(self.getMailData())).then(
              function(res) {
                if (res.success) {
                  var address = _.findLast(self.addresses, function(address) {
                    return self.model.address == address.id;
                  });
                  location.href = Kooboo.Route.Get(
                    Kooboo.Route.Email.SentPage,
                    {
                      address: address.address
                    }
                  );
                }
              }
            );
          }
        });
      },
      removeAttachment: function(m) {
        Kooboo.EmailAttachment.DeleteAttachment({
          filename: m.fileName
        }).then(function(res) {
          if (res.success) {
            self.model.attachments = self.model.attachments.filter(function(f) {
              return f != m;
            });
          }
        });
      }
    },
    watch: {
      contentLoaded: function(value) {
        if (value) {
          this.$nextTick(function() {
            $("#attachments").change(function() {
              function upload(file) {
                var data = new FormData();
                data.append("fileName", file.name);
                data.append("file", file);

                Kooboo.EmailAttachment.AttachmentPost(data).then(function(res) {
                  if (res.success) {
                    self.model.attachments.push(res.model);
                  }
                });
              }

              var files = this.files;

              if (files[0]) {
                if (files[0]["size"]) {
                  if (files[0].size / 1024 / 1024 <= 10) {
                    upload(files[0]);
                  } else {
                    window.info.show(
                      Kooboo.text.info.fileSizeLessThan + "10MB"
                    );
                  }
                } else {
                  upload(files[0]);
                }
              }

              $(this).val("");
            });
          });
        }
      },
      "receiverAddresses.selected": function(value) {
        this.model.receiverAddresses = value;
      },
      "ccAddresses.selected": function(value) {
        this.model.ccAddresses = value;
      },
      "bccAddresses.selected": function(value) {
        this.model.bccAddresses = value;
      }
    }
  });
</script>
